package com.demo.modules.mq.rabbit.service;

import com.demo.common.core.utils.uuid.IdUtils;
import com.demo.modules.mq.rabbit.RabbitAnnouncementMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.concurrent.ListenableFutureCallback;

/**
 * 消息生产者
 *
 * @author Rog
 */
@Slf4j
@Component
public class RabbitMessageProducerService {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 发送到队列
     *
     * @throws InterruptedException
     */

    public void contextLoads(RabbitAnnouncementMessage rabbitAnnouncementMessage) {
        String queueName = "simple.queue01";
        // 发送消息
        rabbitTemplate.convertAndSend(queueName, rabbitAnnouncementMessage);
    }

    /**
     * 回调消息
     *
     * @throws InterruptedException
     */
    public void returnMessage() {
        //创建cd（callback）
        CorrelationData cd = new CorrelationData(IdUtils.randomUuid());
        //添加ConfirmCallback
        cd.getFuture().addCallback(new ListenableFutureCallback<CorrelationData.Confirm>() {
            @Override
            public void onFailure(Throwable ex) {
                log.error("回调消息失败", ex);
            }

            @Override
            public void onSuccess(CorrelationData.Confirm result) {
                log.debug("收到confirm back，开始发送消息");
                if (result.isAck()) {
                    log.debug("消息发送成功, 收到ack");
                } else {
                    log.error("消息发送失败，收到nack,原因{}", result.getReason());
                }
            }
        });
        //发送的消息
        RabbitAnnouncementMessage rabbitAnnouncementMessage = new RabbitAnnouncementMessage();
        rabbitAnnouncementMessage.setId("1");
        rabbitAnnouncementMessage.setContent("helle,tow queue");
        rabbitTemplate.convertAndSend("simple.queue01", rabbitAnnouncementMessage, cd);
    }

    /**
     * 发送到队列
     *
     * @throws InterruptedException
     */
    public void workQueue1() throws InterruptedException {
        //队列名称
        String queueName = "work.queue02";
        for (int i = 0; i < 20; i++) {
            //发送的消息
            RabbitAnnouncementMessage rabbitAnnouncementMessage = new RabbitAnnouncementMessage();
            rabbitAnnouncementMessage.setId(i + "");
            rabbitAnnouncementMessage.setContent("你好，workQueue_" + i);
            rabbitTemplate.convertAndSend(queueName, rabbitAnnouncementMessage);
            Thread.sleep(20);
        }
    }
}

